2023/12/231965字符

原型

在 ECMAScript 中,状态和方法由对象携带,而结构、行为和状态都是继承的。

Person.prototype.name = "wang";
function Person (name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
var person = new Person('li', 35, 'zi');
// 用原型的特点提取共用属性(高内聚,弱偶合)

Car.prototype = {
    height : 1400,
    lang : 4900,
    carName : "BWM"
}
function Car (color, owner) {
    this.color = color;
    this.owner = owner;
}
var car = new Car('red', 'yubo.yang');

delete car.carName;  // 删除原型属性

Car.prototype = {
    constructor : Person
}
Car.constructor  //--> function Person(){}  认贼作父
car.__proto__ = Person  // 原型的连接方式

原型链

Grand.prototype.lastName = 'deng';
function Grand(){

}
var grand = new Grand();
Father.prototype = grand;
function Father(){
    this.name = 'xuming';
}
var father = new Father();
Son.prototype = father;
function Son(){
    this.hobbit = 'smoke';
}
var son = new Son();
son.hobbit  //--> 'smoke'
son.name  //--> 'xuming'
son.lastName  //--> 'deng'

// 绝大多数对象的最终都会继承自 Object.prototype
Object.create(null);  // .create() 除外

Number.prototype.toString = function(){
    return "haha";
}  // 方法重写

person.prototype = {
    toString : function(){
        return "hehe";
    }
}  // 方法中断重写

var obj = Object.create(null);  // .create 方法没有 toString() 方法
obj.toString = function(){
    return 'a';
}
document.write(obj);  // document.write() 方法会通过调用 toString 方法来打印

原型链的作用

  • 之所以存在原型链,是因为 JS 要实现面相对象,原型是实现面向对象的手段之一;
  • 一个支持面向对象的语言必须做到:能够判断一个实例的类型。原型的存在避免了类型丢失